﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using AnyOffice.SMS.ServiceReferenceSMS1;
using AnyOffice.Common;
using System.Xml;
using System.Timers;
using System.Text.RegularExpressions;

namespace AnyOffice.SMS
{
    public partial class MainService : ServiceBase
    {

        private static string loginName = ConfigHelper.GetConfigString("SMSLoginName");
        private static string passWord = ConfigHelper.GetConfigString("SMSPassWord");
        private static string smsKind = ConfigHelper.GetConfigString("SMSKind");

        public MainService()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            this.timer1.Enabled = true;
            this.timer1.Interval = int.Parse(ConfigHelper.GetConfigString("CheckTime")) + 5000;
            this.timer2.Enabled = true;
            this.timer2.Interval = int.Parse(ConfigHelper.GetConfigString("CheckTime"));
        }

        protected override void OnStop()
        {
            this.timer1.Enabled = false;
            this.timer2.Enabled = false;
        }

        private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            //AnyOffice.BLL.Mobile_Receive bll = new BLL.Mobile_Receive();
            //AnyOffice.BLL.Mobile  bllsms = new BLL.Mobile();
            //DataSet ds = new DataSet();
            ////().
            //DataTable dt = GetSMS();
            //foreach (DataRow dr in dt.Rows)
            //{
            //    string scontent = dr["MsgContext"].ToString().Replace('#','#');
            //    string id = GetValue(scontent, "#", "#");
            //    int mobileid =0;
            //    int.TryParse(id, out mobileid);
                
            //    if (mobileid != 0)
            //    {

            //        AnyOffice.Model.Mobile_Receive model = new Model.Mobile_Receive();
            //        ds = bllsms.GetList(1, "MobileId=" + mobileid);
            //        if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            //        {
            //            model.ToId = ds.Tables[0].Rows[0]["FromId"].ToString();
            //        }
            //        model.SendTime = DateTime.Now;
            //        model.FromId = new AnyOffice.BLL.Users().GetUserIDByMobile(dr["Mobile"].ToString());
            //        model.Content = dr["MsgContext"].ToString();
            //        model.Phone =dr["Mobile"].ToString();
            //        model.MobileCode = mobileid;

            //      int i =  bll.Add(model);
                   
            //    }
        
            //}


        }
        /// <summary>
        /// 获取第一个#号和第二个#之间的字符串
        /// </summary>
        /// <param name="str"></param>
        /// <param name="s"></param>
        /// <param name="e"></param>
        /// <returns></returns>
        public static string GetValue(string str, string s, string e)
        {
            Regex rg = new Regex("(?<=(" + s + "))[.\\s\\S]*?(?=(" + e + "))", RegexOptions.Multiline | RegexOptions.Singleline);
            return rg.Match(str).Value;
        }
        private void timer2_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            #region 读取mobile表中的数据

            DataSet dsMobile = new DataSet();

            //dsMobile = new AnyOffice.BLL.Mobile().GetList(1, "SendFlag=0 and SendTime<=getdate() order by SendTime");

            //if (dsMobile != null && dsMobile.Tables.Count > 0 && dsMobile.Tables[0].Rows.Count > 0)
            //{
              
              
            //    string scontent = "";
            //    foreach (DataRow dr in dsMobile.Tables[0].Rows)
            //    {
            //        if (dr["NeedReceive"].ToString() == "1")
            //        {
            //            scontent = dr["Content"].ToString() + "请回复#" + dr["mobileId"].ToString() + "#+内容回复。";
            //        }
            //        else
            //        {
            //            scontent = dr["Content"].ToString();
            //        }

            //        if (SendSMS(dr["phone"].ToString(), scontent))
            //        {
            //            new AnyOffice.BLL.Mobile().CancelRemind(dr["mobileId"].ToString());
            //        }
                  
                   
            //    }
            //}

            #endregion
        }


        /// <summary>
        /// 发送短信
        /// </summary>
        /// <param name="phoneNumber">手机号码；格式13700000000;13700000001</param>
        /// <param name="smsContent">短信内容</param>
        /// <returns></returns>
        public bool SendSMS(string phoneNumber, string smsContent)
        {

            SmsServiceSoapClient sms = new SmsServiceSoapClient();
            System.Xml.XmlNode sninfo;
            sninfo = sms.SendEx(loginName, passWord, smsKind, phoneNumber, "88", smsContent);
            XmlDocument document = new XmlDocument();
            document.LoadXml(sninfo.OuterXml);

            if (document.SelectSingleNode("Response/Code").InnerXml == "0"
                || document.SelectSingleNode("Response/Code").InnerXml == "13"
                || document.SelectSingleNode("Response/Code").InnerXml == "14"
                || document.SelectSingleNode("Response/Code").InnerXml == "15"
                || document.SelectSingleNode("Response/Code").InnerXml == "20"
                || document.SelectSingleNode("Response/Code").InnerXml == "21"
                || document.SelectSingleNode("Response/Code").InnerXml == "22"
                || document.SelectSingleNode("Response/Code").InnerXml == "23")
            {
                return true;
            }
            else
            {
                return false;
            }

        }

        /// <summary>
        /// 接收网关短信
        /// </summary>
        /// <returns>DataTable；Mobile/MsgContext;手机号，短信内容</returns>
        public DataTable GetSMS()
        {

            SmsServiceSoapClient sms = new SmsServiceSoapClient();

            System.Xml.XmlNode sninfo;
            sninfo = sms.GetMo(loginName, passWord, smsKind);

     
            DataTable dt = new DataTable();
            dt.Columns.Add("Mobile", typeof(System.String));
            dt.Columns.Add("MsgContext", typeof(System.String));
            XmlDocument document = new XmlDocument();
            XmlDocument documentl = new XmlDocument();
            string mobile = "";
            string contentmsg = "";
            document.LoadXml(sninfo.OuterXml);//sninfo.OuterXml
            XmlNodeList nodeList = document.SelectNodes("MoReport/MoSms");

            foreach (XmlNode xn in nodeList)
            {
                DataRow dr = dt.NewRow();
                documentl.LoadXml(xn.OuterXml);
                mobile = documentl.SelectSingleNode("MoSms/Mobile").InnerXml;
                contentmsg = documentl.SelectSingleNode("MoSms/MsgContext").InnerXml;
                dr["Mobile"] = mobile;
                dr["MsgContext"] = contentmsg;
                dt.Rows.Add(dr);

            }

            return dt;



        }

       
    }
}
